package com.sl.pmpclient.utils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

/**
 * 访问http的工具类
 * 
 * @author 烁灵
 * 
 */
public class HttpUtil {
	private static String BASE_URL = "http://25.127.187.22/PMPServer/";
	private static String CHAR_ENCODE = "utf-8";
	private static NameValuePair MOBIL_MODE = new BasicNameValuePair("mobile",
			"true");
	private static HttpClient httpClient = new DefaultHttpClient();

	/**
	 * 构造完整url路径
	 * 
	 * @param urlstr
	 * @return
	 */
	private static String getFullURL(String urlstr) {
		return BASE_URL + urlstr;
	}

	/**
	 * 使用get请求url 实现上调用了post请求
	 * 
	 * @param urlstr
	 * @return json数据
	 * @throws IOException
	 * @throws ClientProtocolException
	 */
	public static String getRequest(String urlstr)
			throws ClientProtocolException, IOException {
		return postRequest(urlstr, null);
	}

	/**
	 * 使用post请求url
	 * 
	 * @param urlstr
	 * @param param
	 * @return json数据
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public static String postRequest(String urlstr, Map<String, String> param)
			throws ClientProtocolException, IOException {
		HttpPost httpPost = new HttpPost(getFullURL(urlstr));
		List<NameValuePair> paramlist = new ArrayList<NameValuePair>();
		// 设置手机模式参数
		paramlist.add(MOBIL_MODE);
		// 设置参数列表
		if (param != null) {
			for (String key : param.keySet()) {
				paramlist.add(new BasicNameValuePair(key, param.get(key)));
			}
		}
		httpPost.setEntity(new UrlEncodedFormEntity(paramlist, CHAR_ENCODE));
		// 发送请求
		HttpResponse httpResponse = httpClient.execute(httpPost);
		if (httpResponse.getStatusLine().getStatusCode() == 200) {
			return EntityUtils.toString(httpResponse.getEntity());
		}
		return null;
	}
}
